/*
 * Copyright (c) 2019. seven studio. @chengdu
 * seven studio in chengdu by lb
 * this project for snmp tool
 */

package com.xlx.openLink.threadtask.basetask;


import com.xlx.openLink.entity.pojo.Device;
import com.xlx.openLink.service.DeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class DevSearchService {


    private ConcurrentLinkedQueue<Device> deviceList = new ConcurrentLinkedQueue<>();
    @Autowired
    private DeviceService deviceService;


    public ConcurrentLinkedQueue<Device> searchDev(List<Device> list) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(20, 50, 30L, TimeUnit.SECONDS, new LinkedBlockingQueue());
        this.spList(list).forEach(e -> {
            executor.execute(new DevSearchTask(deviceList, e, deviceService));
        });
        executor.shutdown();
        try {
            if (!executor.awaitTermination(500, TimeUnit.SECONDS)) {
                System.out.println("线程池没有关闭");
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
            e.printStackTrace();
            log.info("线程报错");
        }
        return deviceList;
    }


    private List<List<Device>> spList(List<Device> list) {
        List<List<Device>> lists = new ArrayList<>();
        int loopCount = list.size() / 20;
        int left = list.size() % 20;
        for (int i = 0; i < loopCount; i++) {
            int fromIndex = i * 20;
            lists.add(list.subList(fromIndex, fromIndex + 20));
        }
        if (left > 0) {
            int fromIndex = loopCount * 20;
            lists.add(list.subList(fromIndex, fromIndex + 20));
        }
        return lists;
    }


}
